package com.jy.api.controller.member;

import com.jy.api.dao.MemberDao;
import com.jy.api.domain.CouponInstanceStatus;
import com.jy.api.domain.Member;
import com.jy.api.exception.MyException;
import com.jy.api.service.CouponInstanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * Created by lihu on 2017/11/20.
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/member", produces = "application/json;charset=utf-8")
public class CouponInstanceController {

    @Autowired
    MemberDao memberDao;

    @Autowired
    CouponInstanceService couponInstanceService;

    /**
     * 获取会员优惠卷类列表
     *
     * @param openid
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{openid}/coupon-instance/list")
    public ResponseEntity getMemberStatusCouponInstance(@PathVariable String openid,
                                                        @RequestParam(name = "storeId") String storeId,
                                                        @RequestParam(name = "status", defaultValue = "NORMAL") CouponInstanceStatus status,
                                                        @PageableDefault(value = 10, sort = {"endTime"}, direction = Sort.Direction.ASC) Pageable pageable) {
        try {
            Member member = memberDao.findByOpenId(openid);
            if (member == null) {
                return new ResponseEntity("你不是店铺会员！请先成为会员！", HttpStatus.BAD_REQUEST);
            }

            return ResponseEntity.ok(couponInstanceService.getMemberStatusCouponInstance(member.getId(), status, storeId, pageable));

        } catch (Exception ex) {
            log.error("getMemberStatusCouponInstance is error==> openid:{},status:{}", openid, status, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 获取优惠卷详情
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "{couponInstanceId}/coupon-instance")
    public ResponseEntity getCouponInstancedetails(@PathVariable String couponInstanceId) {
        try {
            return ResponseEntity.ok(couponInstanceService.getCouponInstanceDetails(couponInstanceId));
        } catch (MyException ex) {
            log.error("getCouponInstancedetails is error=>id:{}", couponInstanceId, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("getCouponInstancedetails is error=>id:{}", couponInstanceId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
